package com.javalab._6feature._7io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class _3StringIO {
    public static void main(String[] args) throws IOException {
        // 准备好文件
        File folder = new File("D:/myfolder");
        folder.mkdir();
        File file = new File("D:/myfolder/1.txt");
        file.createNewFile();

        // 写入字符串到文件
        String text = "我爱中国!";
//        String wrap = "\r\n";// 换行符
        String wrap = System.getProperty("line.separator");// 自动适配linux windows mac系统的换行符
        OutputStream outputStream = new FileOutputStream(file);
        outputStream.write(text.getBytes("UTF-8"));
        outputStream.write(wrap.getBytes("UTF-8"));
        outputStream.write(text.getBytes("UTF-8"));
        // 必须关闭资源，以免一直占用，极端情况会导致资源耗尽
        outputStream.close();

        // 读取字符串输出到控制台
        InputStream inputStream = new FileInputStream("D:/myfolder/1.txt");
        // 读取内容长度
        int available = inputStream.available();
        // 创建字节数组用来保存读取的内容
        byte[] bytes = new byte[available];
        // 读取内容
        inputStream.read(bytes);
        // 输出
        System.out.println("读取文件内容:");
        System.out.println(new String(bytes,"UTF-8"));
        inputStream.close();
    }
}
